package com.ibm.member.common.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order
@Aspect
@Component
public class LogAspect {

    private static final Logger Logger = LoggerFactory.getLogger(LogAspect.class);

    @Pointcut("execution(public * com.ibm.member.service.impl.*.*(..))")
    public void logServiceAspect() {
    }

    @Before("logServiceAspect()")
    public void beforeInvoking(JoinPoint point) {
        log(point, null);
    }

    @AfterReturning(pointcut = "logServiceAspect()", returning = "result")
    public void afterReturning(JoinPoint point, Object result) {
        log(point, result == null ? "null" : result);
    }

    @AfterThrowing(pointcut = "logServiceAspect()", throwing = "result")
    public void afterThrowing(JoinPoint point, Exception result) {
        log(point, result);
    }

    private static void log(JoinPoint point, Object result) {
        String sign = "Start";
        if (result != null) {
            sign = "End";
            if (result instanceof Exception)
                sign = "Exception";
        }

        Signature signature = point.getSignature();

        StringBuilder sb = new StringBuilder();
        sb.append("接口名:").append(signature);
        sb.append(sign);

        if (sign.equals("Start")) {
            sb.append("入参:");
            for (Object agr : point.getArgs())
                sb.append(String.valueOf(agr));
        } else if (sign.equals("End")) {
            sb.append("出参");
            sb.append(String.valueOf(result));
        } else {
            sb.append("异常");
            sb.append(String.valueOf(result));
        }
        Logger.info(sb.toString());
    }
}